/**
 * 自动注入分页请求
 * @param  apiOrUri 要请求的地址或者apis中定义的方法 地址必须是自定义apis
 * @param  spread 是否对外提供默认的方法
 * @param  callback 是否对外暴露数据，可以用来修改数据结构
 * @returns
 */
export function useList<T = any>(apiOrUri: string | ApiCall<T>, spread: boolean = true, callback?: Function | undefined) {
  const tableData: TableData<T> = reactive({ meta: { page: 1, size: 10, total: 1 }, lists: [], extra: {} })

  const loadingList = ref(false)

  /**
   * 获取列表
   */
  const getList = async () => {
    let data = {} as ResPage<T>

    const req = apiOrUri as Function
    data = await req({ page: tableData.meta.page, size: tableData.meta.size, ...tableData.extra }, loadingList)

    callback && (await callback(data.lists))
    tableData.lists = data.lists
    tableData.meta = data.meta
  }

  const changePage = (page: number) => {
    tableData.meta.page = page
    getList()
  }
  const handleSizeChange = (size: number, init?: boolean) => {
    tableData.meta.size = size
    if (!init) {
      getList()
    }
  }

  const resetList = (cleanExtra: boolean, filter: any) => {
    tableData.lists = []
    tableData.meta = { page: 1, size: 10, total: 1 }
    if (cleanExtra) {
      tableData.extra = {}
      if (filter != null) {
        tableData.extra = filter
      }
    }
  }

  if (spread) {
    provide('tableData', tableData)
    provide('getList', getList)
    provide('changePage', changePage)
    provide('handleSizeChange', handleSizeChange)
    provide('resetList', resetList)
  }

  return {
    loadingList,
    tableData,
    getList,
    changePage,
    handleSizeChange,
    resetList
  }
}
